package com.fhj.movie.activity;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.regex.Pattern;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.fhj.movie.entity.City;
import com.fhj.movie.interfaces.CallbackInterface;
import com.fhj.movie.interfaces.MyApplication;
import com.fhj.movie.view.ABCView;
import com.fhj.movie.view.ABCView.OnTouchingABCChangedListener;
import com.fhj.movie_fhj_01.R;
import com.fhj.movie_main.MainActivity;
import com.fhj.utils.HttpConnectionUtils;

public class FHCityListActivity extends Activity implements
		OnTouchingABCChangedListener, OnItemClickListener {

	private TextView currentCity;// 定位城市
	private ABCView abcView;
	private ListView cityListView;
	private TextView currentABC;
	private RequestQueue queue;

	private ArrayList<City> cities;
	private CityListAdapter adapter;
	private final static String URL = "http://piao.163.com/m/base_data.html?"
			+ "updateTime=&apiVer=14&mobileType=android"
			+ "&deviceId=08:00:27:f4:e2:00&channel=netease&ver=4.8&city=440300";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.citylist_layout);
		currentCity = (TextView) findViewById(R.id.fh_current_city);
		currentABC = (TextView) findViewById(R.id.fh_current_abc_show);
		cityListView = (ListView) findViewById(R.id.fh_city_list);
		abcView = (ABCView) findViewById(R.id.fh_city_abc);
		abcView.setOnTouchingABCChangedListener(this);
		queue = Volley.newRequestQueue(this);

		rotate = (ImageView) findViewById(R.id.fh_rotate_img);
		animation = AnimationUtils.loadAnimation(this, R.anim.load_rotate);
		LinearInterpolator interpolator = new LinearInterpolator();

		animation.setInterpolator(interpolator);
//		Animation activityAnimation = AnimationUtils.loadAnimation(this,
//				R.anim.city_upto_anim);

		overridePendingTransition(R.anim.city_upto_anim, R.anim.city_up_anim);

		doWork();
		cities = new ArrayList<City>();

		cityListView.setOnItemClickListener(this);
		queue.add(new JsonObjectRequest(Request.Method.POST, URL, null,
				new Response.Listener<JSONObject>() {

					@Override
					public void onResponse(JSONObject arg0) {
						// TODO 自动生成的方法存根
						try {
							JSONArray cityList = arg0.getJSONArray("cityList");
							Log.i("----------", cityList.toString());
							for (int index = 0; index < cityList.length(); index++) {
								JSONObject obj = cityList.getJSONObject(index);
								String name = obj.getString("name");
								String spell = obj.getString("spell");
								String code = obj.getString("code");
								cities.add(new City(name, spell, code));

							}
							sortCity(cities);
							adapter = new CityListAdapter();
							cityListView.setAdapter(adapter);
							cityListView.setTextFilterEnabled(true);

						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}, new Response.ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError arg0) {
						// TODO 自动生成的方法存根
						Toast.makeText(getApplicationContext(), "Volley数据请求失败",
								Toast.LENGTH_SHORT).show();
					}
				}));

	}

	public int abcIndex(String s) {
		int i = 0;
		for (; i < cities.size(); i++) {
			if (cities.get(i).getSpell().startsWith(s)||cities.get(i).getSpell().startsWith(s.toLowerCase())) {
				break;
			}
		}
		return i;
	}

	

	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			if (msg.what == 1) {
				if (msg.obj instanceof String) {
					rotate.clearAnimation();
					rotate.setVisibility(View.GONE);
					currentCity.setText((CharSequence) msg.obj);
				}

			}
		};
	};
	private ImageView rotate;
	private Animation animation;

	@Override
	public void onTouchingABCChanged(String s) {
		// TODO
		if (abcIndex(s) > 0) {
			int position = abcIndex(s);
		    
			cityListView.setSelection(position);
			currentABC.setText(s);
			currentABC.setVisibility(View.VISIBLE);
			handler.postDelayed(new Runnable() {

				@Override
				public void run() {
					// TODO
					currentABC.setVisibility(View.INVISIBLE);
				}
			}, 1000);
		}

	}

	class CityListAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return cities.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			
			return cities.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			ViewHolder holder = null;
			if (convertView == null) {
				convertView = LayoutInflater.from(getApplicationContext())
						.inflate(R.layout.city_lv_item, parent, false);
				holder = new ViewHolder();
				holder.txtCatalog = (TextView) convertView
						.findViewById(R.id.city_lv_item_catalog);
				holder.txtTitle = (TextView) convertView
						.findViewById(R.id.city_lv_item_title);

			    convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			City city = cities.get(position);
			if(position==0){
				holder.txtCatalog.setText(("" + city.getSpell().charAt(0)).toUpperCase());
				holder.txtCatalog.setVisibility(View.VISIBLE);
			}
			
			else if (position > 0) {
				City city2 = cities.get(position-1);
				if (city.getSpell().charAt(0) == city2.getSpell().charAt(0)) {
					//holder.txtCatalog.setText(("" + city.getSpell().charAt(0)).toUpperCase());
					holder.txtCatalog.setVisibility(View.GONE);
				}
				else if(city.getSpell().charAt(0) > city2.getSpell().charAt(0)){
					holder.txtCatalog.setText(("" + city.getSpell().charAt(0)).toUpperCase());
					holder.txtCatalog.setVisibility(View.VISIBLE);
				}
			}
			if (city.getName().endsWith("市")) {
				
				
				holder.txtTitle.setText(city.getName());

			} else {
				
				holder.txtTitle.setText(city.getName() + "市");

			}
			return convertView;
		}

		class ViewHolder {
			TextView txtCatalog;
			TextView txtTitle;
		}

	}

	private City city2;
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {

		String cityName = cities.get(position).getName();
		int code = Integer.parseInt(cities.get(position).getCode());

		MyApplication application = (MyApplication) getApplication();
		application.setCityName(cityName);
		application.setCityCode(code);
		Log.d("currentCity", cityName + "," + code);
		Intent intent = new Intent(FHCityListActivity.this, MainActivity.class);
		intent.putExtra("cityName", cityName);
		FHCityListActivity.this.setResult(RESULT_OK, intent);
		FHCityListActivity.this.finish();

	}

	private void doWork() {
		rotate.setAnimation(animation);

		String msg = "";
		LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

		if (locationManager
				.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
			msg = "无法定位您所在的城市，请手动选择";

		} else {

			Criteria criteria = new Criteria();
			// 获得最好的定位效果
			criteria.setAccuracy(Criteria.ACCURACY_FINE);
			criteria.setAltitudeRequired(false);
			criteria.setBearingRequired(false);
			criteria.setCostAllowed(false);
			// 使用省电模式
			criteria.setPowerRequirement(Criteria.POWER_LOW);
			// 获得当前的位置提供者
			String provider = locationManager.getBestProvider(criteria, true);
			// 获得当前的位置
			Location location = locationManager.getLastKnownLocation(provider);
			if (location != null) {

				Geocoder gc = new Geocoder(this);
				List<Address> addresses = null;
				try {
					addresses = gc.getFromLocation(location.getLatitude(),
							location.getLongitude(), 1);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if (addresses.size() > 0) {
					msg = addresses.get(0).getLocality();

				}
			} else {
				msg = "无法定位您所在的城市，请手动选择";
			}
		}
		Message message = handler.obtainMessage(1);
		message.obj = msg;
		handler.sendMessageDelayed(message, 1000);
	}

	public void sortCity(ArrayList<City> cities) {
		Collections.sort(cities, cityComparator);
	}

	private Comparator<City> cityComparator = new Comparator<City>() {

		@Override
		public int compare(City arg0, City arg1) {
			// TODO Auto-generated method stub
			return arg0.getSpell().compareTo(arg1.getSpell());
		}

	};

}
